#include<iostream>
#include<string>
#include<thread>
#include<mutex>


class sClass {
private:
    sClass() {} // 私有化构造函数

private:
    static sClass* myInstance; // 静态成员类内声明
    class helpDelete { // 定义一个辅助类，用于释放这个单例对象
    public:
        ~helpDelete() {
            if (sClass::myInstance) {
                delete myInstance;
                sClass::myInstance = nullptr;
                std::cout<<"已析构"<<std::endl;
            }
        }
    };

public:
    static sClass* getInstance(); // 成员函数类内声明
    void thisIsTest();
    static void createInstance(); // 也需要是静态

};

sClass* sClass::myInstance = nullptr; // 静态成员类外初始化
// std::mutex getMutex;

std::once_flag myflag;

void sClass::createInstance() {
    myInstance = new sClass();
    static helpDelete del;
    return;
}

sClass* sClass::getInstance() {
    // if (myInstance == nullptr) {
    //     std::lock_guard<std::mutex> mylock(getMutex); // 加锁
    //     if (myInstance == nullptr) {
    //         myInstance = new sClass();
    //         static helpDelete del;
    //     }
    // }
    std::call_once(myflag, createInstance); // 只会执行一次new
    return myInstance;
}

void sClass::thisIsTest() {

    std::cout<< "地址" << this <<std::endl;

}

void threadEntry() {
    sClass *myPtr1 = sClass::getInstance(); // 创建一个单例类
    std::cout<< "thread start and end" <<std::endl;
    return;
}

int main() {
    std::thread mythread1(threadEntry);
    std::thread mythread2(threadEntry);
    mythread1.join();
    mythread2.join();
    return 0;
}